package com.example.chirdrenserver.Service.AdminService.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chirdrenserver.Pojo.dto.BasePage;
import com.example.chirdrenserver.Pojo.dto.admin.CommentDTO;
import com.example.chirdrenserver.Pojo.entity.Comment;
import com.example.chirdrenserver.Pojo.entity.User;
import com.example.chirdrenserver.Pojo.vo.admin.CommentVO;
import com.example.chirdrenserver.Service.AdminService.AdminCommentService;
import com.example.chirdrenserver.Service.AdminService.UserService;
import com.example.chirdrenserver.mapper.CommentMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AdminCommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements AdminCommentService {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private UserService userService;

    @Override
    public boolean addComment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO, comment);
        comment.setCreateTime(LocalDateTime.now());
        return save(comment);
    }

    @Override
    public boolean replyComment(Long parentId, CommentDTO commentDTO) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO, comment);
        comment.setParentCommentId(parentId);
        comment.setCreateTime(LocalDateTime.now());
        return save(comment);
    }

    @Override
    public boolean deleteComment(Long commentId) {
        return removeById(commentId);
    }

    @Override
    public CommentVO getCommentById(Long commentId) {
        Comment comment = getById(commentId);
        if (comment == null) {
            return null;
        }
        CommentVO vo = new CommentVO();
        BeanUtils.copyProperties(comment, vo);
        // 添加用户信息
        addUserInfo(vo);
        return vo;
    }

    @Override
    public IPage<CommentVO> getCommentList(Long postId, BasePage basePage) {
        //分页
        Page<Comment> page = new Page<>(basePage.getPage(), basePage.getLimit());
        // 查询所有相关评论
        QueryWrapper<Comment> Wrapper = new QueryWrapper<>();
        if (postId != null) {
            Wrapper.eq("post_id", postId);
        }

        // 添加排序条件
        Wrapper.orderByDesc("create_time");
        IPage<Comment> commentIPage = page(page, Wrapper);

        // 转换为VO分页对象
        return commentIPage.convert(this::convertToVO);
    }

    private List<CommentVO> buildCommentTree(List<Comment> allComments) {
        // 转换为VO列表并补充用户信息
        List<CommentVO> commentVOs = allComments.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 存储顶级评论（没有父评论的评论）
        List<CommentVO> topLevelComments = new ArrayList<>();

        // 使用Map存储所有评论，key为评论ID
        Map<Long, CommentVO> commentMap = new HashMap<>();
        for (CommentVO comment : commentVOs) {
            commentMap.put(comment.getCommentId(), comment);
        }

        // 遍历所有评论，构建树形结构
        for (CommentVO comment : commentVOs) {
            Long parentId = comment.getParentCommentId();
            if (parentId == null || parentId == 0) {
                // 顶级评论
                topLevelComments.add(comment);
            } else {
                // 子评论：找到父评论并添加到其replies列表中
                CommentVO parentComment = commentMap.get(parentId);
                if (parentComment != null) {
                    if (parentComment.getReplies() == null) {
                        parentComment.setReplies(new ArrayList<>());
                    }
                    parentComment.getReplies().add(comment);
                }
            }
        }

        return topLevelComments;
    }

    private IPage<CommentVO> manualPagination(List<CommentVO> allComments, BasePage basePage) {
        // 筛选顶级评论
        List<CommentVO> topLevelComments = allComments.stream()
                .filter(comment -> comment.getParentCommentId() == null || comment.getParentCommentId() == 0)
                .collect(Collectors.toList());

        // 获取分页参数（转换为 int）
        int pageSize = basePage.getPageSize().intValue();
        int currentPage = basePage.getCurrentPage().intValue();

        // 分页计算
        int total = topLevelComments.size();
        int start = (currentPage - 1) * pageSize;
        int end = Math.min(start + pageSize, total);

        // 创建分页对象
        Page<CommentVO> resultPage = new Page<>(basePage.getCurrentPage(), basePage.getPageSize(), total);

        // 获取当前页的数据
        List<CommentVO> currentPageList = start < end ?
                topLevelComments.subList(start, end) :
                Collections.emptyList();

        // 按创建时间倒序排序（最新发布的排在最前面）
        currentPageList.sort(Comparator.comparing(CommentVO::getCreateTime).reversed());

        resultPage.setRecords(currentPageList);

        return resultPage;
    }

    @Override
    public List<CommentVO> getRepliesByParentId(Long parentId) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_comment_id", parentId);

        List<Comment> replies = list(wrapper);

        return replies.stream().map(comment -> {
            CommentVO vo = new CommentVO();
BeanUtils.copyProperties(comment, vo);
            // 添加用户信息
            addUserInfo(vo);
            return vo;
        }).collect(Collectors.toList());
    }

    // 转换方法（补充用户信息）
    private CommentVO convertToVO(Comment comment) {
        CommentVO vo = new CommentVO();
        vo.setCommentId(comment.getCommentId());
        vo.setContent(comment.getContent());
        vo.setCreateTime(LocalDateTime.now());
        BeanUtils.copyProperties(comment, vo);
        // 添加用户信息
        addUserInfo(vo);
        return vo;
    }

    // 添加用户信息到CommentVO
    private void addUserInfo(CommentVO vo) {
        if (vo.getUserId() != null) {
            User user = userService.getUserById(Long.valueOf(vo.getUserId()));
            if (user != null) {
                vo.setNickname(user.getNickname());
                vo.setAvatar(user.getAvatarFileKey());
            }
        }
    }
}